/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-03-29 09:37:19
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-09-24 17:38:24
 * @FilePath: /vue3-admin/src/service/biz/useRole.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
    readRoleList,
    RoleListParam,
    readRoleDetail,
    createOrUpdateRole,
    RoleParam,
    deleteRole
} from '@/api/role';
import { ref } from 'vue';
import type { RoleListItem, RoleDetial } from '@/typings/api/role';
import { useEnum } from '@/service/useEnum';

export { RoleListParam, RoleParam };

export const useRole = () => {
    const total = ref(0);
    const list = ref<RoleListItem[]>([]);
    const loading = ref(false);
    const { getRoleTypes } = useEnum();
    const { update: roleTypesUpdate } = getRoleTypes();

    const getList = (param: RoleListParam) => {
        if (loading.value) return;
        loading.value = true;
        return readRoleList(param)
            .then((res) => {
                list.value = res.data.records;
                total.value = res.data.total;
                return res;
            })
            .finally(() => {
                loading.value = false;
            });
    };

    const detail = ref<RoleDetial>();
    const detailLoading = ref(false);

    const getDetail = (id: number) => {
        if (detailLoading.value) return;
        detailLoading.value = true;
        return readRoleDetail(id)
            .then((res) => {
                detail.value = res.data;
                return res;
            })
            .finally(() => {
                detailLoading.value = false;
            });
    };

    const updateLoading = ref(false);
    const updateRole = (param: RoleParam) => {
        if (updateLoading.value) return;
        updateLoading.value = true;
        return createOrUpdateRole(param)
            .then((res) => {
                roleTypesUpdate();
                return res;
            })
            .finally(() => {
                updateLoading.value = false;
            });
    };

    const removeLoading = ref(false);
    const removeRole = (id: number) => {
        if (removeLoading.value) return;
        removeLoading.value = true;
        return deleteRole(id)
            .then((res) => {
                roleTypesUpdate();
                return res;
            })
            .finally(() => {
                removeLoading.value = false;
            });
    };

    return {
        loading,
        total,
        list,
        getList,
        detail,
        detailLoading,
        getDetail,
        updateRole,
        updateLoading,
        removeLoading,
        removeRole
    };
};
